﻿using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Group;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace LyncSilverlightApplication
{
    /// <summary>
    /// addContactUri.xaml の相互作用ロジック
    /// </summary>
    public partial class addContactUri : ChildWindow, INotifyPropertyChanged
    {
        #region "グローバル変数"
        LyncClient LyncClient;
        ContactManager ContactManager;
        Group OtherContactsGroup;

        public ObservableCollection<ContactInfo> OtherContacts { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region "フォームロード"
        public addContactUri()
        {
            InitializeComponent();
        }

        private void ChildWindow_Loaded_1(object sender, RoutedEventArgs e) 
        {
            try
            {
                OtherContacts = new ObservableCollection<ContactInfo>();
                LyncClient = LyncClient.GetClient();
                ContactManager = LyncClient.ContactManager;
                OtherContactsGroup = GetOtherContactsGroup();
                OtherContactsGroup.ContactAdded += new EventHandler<GroupMemberChangedEventArgs>(OtherContactsGroup_ContactAdded);
                OtherContactsGroup.ContactRemoved += new EventHandler<GroupMemberChangedEventArgs>(OtherContactsGroup_ContactRemoved);
                this.DataContext = this;
                UpdateOtherContactsGroupContactInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region "プライベート機能"
        /// <summary>
        /// Other Contactsグループから連絡先削除機能
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">GroupMemberChangedEventArgs</param>
        void OtherContactsGroup_ContactRemoved(object sender, GroupMemberChangedEventArgs e)
        {
            UpdateOtherContactsGroupContactInfo();
        }

        /// <summary>
        /// Other Contactsグループに連絡先追加機能
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">GroupMemberChangedEventArgs</param>
        void OtherContactsGroup_ContactAdded(object sender, GroupMemberChangedEventArgs e)
        {
            UpdateOtherContactsGroupContactInfo();
        }

        /// <summary>
        /// Other Contactsグループの連絡先情報取得
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">GroupMemberChangedEventArgs</param>
        private void UpdateOtherContactsGroupContactInfo()
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                OtherContacts.Clear();
                foreach (Contact contact in OtherContactsGroup)
                {
                    OtherContacts.Add(new ContactInfo(contact));
                }
                OtherContacts = new ObservableCollection<ContactInfo>(OtherContacts.OrderBy(p => p.DisplayName));
            }), null);
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("OtherContacts"));
            }
        }

        /// <summary>
        /// Other Contactsグループ情報取得
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">GroupMemberChangedEventArgs</param>
        private Group GetOtherContactsGroup()
        {
            foreach (Group group in ContactManager.Groups)
            {
                if (group.Type == GroupType.CustomGroup && group.Name == "Other Contacts")
                {
                    return group;
                }
            }
            return null;
        }

        /// <summary>
        /// 連絡先追加機能
        /// </summary>
        /// <param name="ar">IAsyncResult</param>
        private void AddContact_Callback(IAsyncResult ar)
        {
            try
            {
                OtherContactsGroup.EndAddContact(ar);
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    UpdateOtherContactsGroupContactInfo();
                }), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                            "連絡先を追加する時に、エラーが発生しました。"+ex.Message,
                            "連絡先追加エラー",
                            MessageBoxButton.OK);
                return;
            }
        }

        /// <summary>
        /// 連絡先削除機能
        /// </summary>
        /// <param name="ar">IAsyncResult</param>
        private void RemoveContact_Callback(IAsyncResult ar)
        {
            try
            {
                OtherContactsGroup.EndRemoveContact(ar);
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    UpdateOtherContactsGroupContactInfo();
                }), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                            "連絡先を削除する時に、エラーが発生しました。" + ex.Message,
                            "連絡先削除エラー",
                            MessageBoxButton.OK);
                return;
            }
        }
        #endregion

        #region "ボタンイベント"

        /// <summary>
        /// 閉じるボタンイベント
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">RoutedEventArgs</param>
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        /// <summary>
        /// 連絡先追加ボタンイベント
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">RoutedEventArgs</param>
        private void AddContactButton_Click(object sender, RoutedEventArgs e)
        {
            string contactUri = ContactSipUriTextBox.Text.Trim();
            if (!string.IsNullOrWhiteSpace(contactUri))
            {
                Contact contact = ContactManager.GetContactByUri(contactUri);
                if (contact != null)
                {
                    try
                    {
                        OtherContactsGroup.BeginAddContact(contact, AddContact_Callback, null);
                        ContactSipUriTextBox.Text = string.Empty;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(
                            "連絡先が重複しています" + ex.Message,
                            "連絡先追加エラー",
                            MessageBoxButton.OK);
                        return;
                    }
                }

            }
            else
            {
                ContactSipUriTextBox.Focus();
                MessageBox.Show(
                            string.Format("連絡先Uriを入力してください."),
                            "連絡先追加エラー",
                            MessageBoxButton.OK);
                return;
            }
        }

        /// <summary>
        /// 連絡先削除ボタンイベント
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">RoutedEventArgs</param>
        private void RemoveContactButton_Click(object sender, RoutedEventArgs e)
        {
            if (otherContactsListBox.SelectedItem != null)
            {
                ContactInfo contactInfo = (ContactInfo)otherContactsListBox.SelectedItem;
                MessageBoxResult mbr = MessageBox.Show(
                    string.Format("\"{0}\"連絡先を削除しますか?", contactInfo.DisplayName),
                    "連絡先削除確認",
                    MessageBoxButton.OKCancel);
                if (mbr == MessageBoxResult.OK)
                {
                    try
                    {
                        OtherContactsGroup.BeginRemoveContact(contactInfo.Contact, RemoveContact_Callback, null);
                        ContactSipUriTextBox.Text = string.Empty;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(
                            "連絡先を削除する時に、エラーが発生しました。" + ex.Message,
                            "連絡先削除エラー",
                            MessageBoxButton.OK);
                        return;
                    }
                }
            }
            else
            {
                ContactSipUriTextBox.Focus();
                MessageBox.Show(
                            string.Format("削除する連絡先を選択してください."),
                            "連絡先削除エラー",
                            MessageBoxButton.OK);
                return;
            }
        }
        #endregion
        
    }
    /// <summary>
    /// 連絡先情報取得クラス 
    /// </summary>
    /// <param name=""></param>
    public class ContactInfo
    {
        #region "Get、Set"
        private string displayName = null;
        public string DisplayName
        {
            get
            {
                if (string.IsNullOrEmpty(displayName))
                {
                    return SipUri;
                }
                else
                {
                    return displayName + " (" + SipUri + ")";
                }
            }
        }

        public string SipUri { get; set; }

        public Contact Contact { get; set; }
        #endregion

        #region "連絡先情報取得機能"
        public ContactInfo(Contact contact)
        {
            this.Contact = contact;
            this.SipUri = contact.Uri;
            displayName = (string)this.Contact.GetContactInformation(ContactInformationType.DisplayName);
        }
        #endregion
    }
}

